package com.doge.service.wx.cart;

import com.doge.bean.bo.cart.AddCartBO;
import com.doge.bean.bo.cart.CheckedCartBO;
import com.doge.bean.bo.cart.UpdateCartBO;
import com.doge.bean.pojo.address.Address;
import com.doge.bean.pojo.cart.Cart;
import com.doge.bean.pojo.cart.CartExample;
import com.doge.bean.pojo.coupon.Coupon;
import com.doge.bean.pojo.coupon.CouponExample;
import com.doge.bean.pojo.coupon.CouponUser;
import com.doge.bean.pojo.coupon.CouponUserExample;
import com.doge.bean.pojo.goods.Goods;
import com.doge.bean.pojo.goods.GoodsProduct;
import com.doge.bean.pojo.goods.GoodsProductExample;
import com.doge.bean.pojo.order.Order;
import com.doge.bean.pojo.order.OrderExample;
import com.doge.bean.pojo.user.User;
import com.doge.bean.vo.cart.WxCheckOutVO;
import com.doge.bean.vo.cart.WxIndexVO;
import com.doge.mapper.*;
import com.doge.util.auth.GetSubject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: project2-wechat-mall
 * @description:
 * @author: zhu lei
 * @create: 2021-12-02 22:10
 **/
@Service
public class WxCartServiceImpl implements WxCartService {
    @Autowired
    CartMapper cartMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    AddressMapper addressMapper;

    @Autowired
    CouponUserMapper couponUserMapper;

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    SystemMapper systemMapper;

    @Override
    public Integer fastAdd(AddCartBO addCartBO) {
        // fast add 时候新建一个 cart，即便有相同商品的cart
        Goods goods = goodsMapper.selectByPrimaryKey(addCartBO.getGoodsId());
/*        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andUserIdEqualTo(GetSubject.getUserId()).andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        int data = 0;
        for (Cart cart : carts) {
            if (cart.getGoodsId().equals(addCartBO.getGoodsId())) {
                cart.setNumber(cart.getNumber() + addCartBO.getNumber());
                cartMapper.updateByPrimaryKeySelective(cart);
                data = cart.getNumber();
                return data;
            }
        }*/
        Cart cart = new Cart();
        cart.setAddTime(goods.getAddTime());
        cart.setDeleted(goods.getDeleted());
        cart.setGoodsId(goods.getId());
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setNumber(addCartBO.getNumber());
        cart.setProductId(addCartBO.getProductId());
        cart.setPicUrl(goods.getPicUrl());
        cart.setGoodsName(goods.getName());
        cart.setPrice(goods.getCounterPrice());
        GoodsProduct goodsProduct = goodsProductMapper.selectByPrimaryKey(addCartBO.getProductId());
        cart.setSpecifications(goodsProduct.getSpecifications());
        cart.setChecked(false);
        cart.setUpdateTime(goods.getUpdateTime());
        cart.setUserId(GetSubject.getUserId());
        cart.setDeleted(true);

        cartMapper.insertSelective(cart);
        return cart.getId();

    }

    /*
     * 返回的data是购物车id
     * */
    @Override
    public int addCart(AddCartBO addCartBO) {
        int data = 0;
        Integer goodsId = addCartBO.getGoodsId();
        Integer number = addCartBO.getNumber();
        Integer productId = addCartBO.getProductId();
        Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andUserIdEqualTo(GetSubject.getUserId()).andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        boolean cartIdIsSame = false;
        for (Cart cart : carts) {
            if (cart.getGoodsId().equals(goodsId)) {
                cartIdIsSame = true;
                cart.setNumber(cart.getNumber() + number);
                cartMapper.updateByPrimaryKeySelective(cart);
            }
            data += cart.getNumber();
        }
        if (cartIdIsSame) {
            return data;
        }
        Cart cart = new Cart();
        cart.setAddTime(goods.getAddTime());
        cart.setDeleted(goods.getDeleted());
        cart.setGoodsId(goods.getId());
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setNumber(number);
        cart.setProductId(productId);
        cart.setPicUrl(goods.getPicUrl());
        cart.setGoodsName(goods.getName());
        cart.setPrice(goods.getCounterPrice());

//        cart.setSpecifications(goods.getBrief());

        GoodsProduct goodsProduct = goodsProductMapper.selectByPrimaryKey(productId);

        cart.setSpecifications(goodsProduct.getSpecifications());

        cart.setChecked(false);
        cart.setUpdateTime(goods.getUpdateTime());
        cart.setUserId(GetSubject.getUserId());
        cartMapper.insertSelective(cart);
        //返回的是当前购物车商品总数
        data = number;
        for (Cart cart1 : carts) {
            data += cart1.getNumber();
        }
        return data;
    }

    @Override
    public WxIndexVO checkedCartUser(CheckedCartBO checkedCartBO) {

        Integer isChecked = checkedCartBO.getIsChecked();
        List<Integer> productIds = checkedCartBO.getProductIds();
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andUserIdEqualTo(GetSubject.getUserId()).andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        WxIndexVO wxIndexVO = new WxIndexVO();
        for (Cart cart : carts) {
            for (Integer productId : productIds) {
                if (cart.getProductId().equals(productId)) {
                    cart.setChecked(isChecked != 0);
                    cartMapper.updateByPrimaryKeySelective(cart);
                }
            }
        }
        wxIndexVO.setCartList(carts);
        WxIndexVO.CartTotalDTO cartTotalDTO = new WxIndexVO.CartTotalDTO();
        Integer checkedGoodsCount = 0;
        Integer goodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal("0");
        BigDecimal checkedGoodsAmount = new BigDecimal("0");
        for (Cart cart : carts) {
            if (cart.getChecked()) {
                checkedGoodsCount++;
                checkedGoodsAmount = checkedGoodsAmount.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
            }
            goodsCount++;
            goodsAmount = goodsAmount.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
        }
        cartTotalDTO.setGoodsCount(goodsCount);
        cartTotalDTO.setCheckedGoodsCount(checkedGoodsCount);
        cartTotalDTO.setCheckedGoodsAmount(checkedGoodsAmount);
        cartTotalDTO.setGoodsAmount(goodsAmount);
        wxIndexVO.setCartTotal(cartTotalDTO);
        return wxIndexVO;
    }

    @Override
    public WxCheckOutVO checkOutCart(Integer cartId, Integer addressId, Integer couponId, Integer userCouponId, Integer grouponRulesId) {
        WxCheckOutVO wxCheckOutVO = new WxCheckOutVO();

        //        总价
        BigDecimal goodsTotalPrice = new BigDecimal("0");

//        获取用户id
        Integer userId = GetSubject.getUserId();
//        获取用户对象
        User user = userMapper.selectByPrimaryKey(userId);
        List<Cart> checkedGoodsList = new ArrayList<>();
//        如果购物车id等于0，就代表列出所有被选中的购物车商品列表，不等于零就根据购物车id直接列出选中的购物车商品
        if (cartId == 0) {
            //        获得购物车列表信息
            CartExample cartExample = new CartExample();
            cartExample.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
            List<Cart> carts = cartMapper.selectByExample(cartExample);
            for (Cart cart : carts) {
                if (cart.getChecked()) {
                    checkedGoodsList.add(cart);
                    goodsTotalPrice = goodsTotalPrice.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
                }
            }
        } else {
            Cart cart = cartMapper.selectByPrimaryKey(cartId);
            checkedGoodsList.add(cart);
            goodsTotalPrice = goodsTotalPrice.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
        }

//        通过addressid获取地址信息
        // addressId = 0, 表示没有默认地址；不为0的时候，也判断是自己的地址，还是缓存别的用户的地址
        Address checkedAddress = null;
        if (addressId != 0) {
            checkedAddress = addressMapper.selectByPrimaryKey(addressId);
            if (!userId.equals(checkedAddress.getUserId())) {
                checkedAddress = null;
            }
        }
        CouponUserExample couponUserExample = new CouponUserExample();
        couponUserExample.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        Integer availableCouponLength = 0;
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
        for (CouponUser couponUser : couponUsers) {
            if (couponUser.getStatus() == 0) {
                availableCouponLength++;
            }
        }
        BigDecimal couponPrice = new BigDecimal("0");
        if (couponId != null && couponId != 0 && couponId != -1) {
            Coupon coupon = couponMapper.selectByPrimaryKey(couponId);
            couponPrice = coupon.getDiscount();
        }

//        初始化剩下的变量:还剩下实付、运费、商品合计、团购价格、orderTotalPrice
//        实付
//        优惠券数量
//        couponId选择到优惠券的价格

        // 根据商品总价格 与最低运费价格对比，判断运费
        BigDecimal freightPrice = new BigDecimal(0);
        BigDecimal needFreightMin = new BigDecimal(systemMapper.getMarketSystemByKeyName("market_express_freight_min"));
        if (needFreightMin.compareTo(goodsTotalPrice) > 0) {
            freightPrice = new BigDecimal(systemMapper.getMarketSystemByKeyName("market_express_freight_value"));
        }
        BigDecimal orderTotalPrice = goodsTotalPrice.subtract(couponPrice).add(freightPrice);
//        开始赋值
        BigDecimal actualPrice = orderTotalPrice;


        wxCheckOutVO.setCartId(cartId);
        wxCheckOutVO.setAddressId(addressId);
        wxCheckOutVO.setCouponId(couponId);
        wxCheckOutVO.setUserCouponId(userCouponId);
        wxCheckOutVO.setGrouponRulesId(grouponRulesId);
        wxCheckOutVO.setFreightPrice(freightPrice);
        wxCheckOutVO.setActualPrice(actualPrice);
        wxCheckOutVO.setGoodsTotalPrice(goodsTotalPrice);
        wxCheckOutVO.setGrouponPrice(new BigDecimal(0));
        wxCheckOutVO.setOrderTotalPrice(orderTotalPrice);
        wxCheckOutVO.setCouponPrice(couponPrice);
        wxCheckOutVO.setAvailableCouponLength(availableCouponLength);
        //        购物车赋值
        wxCheckOutVO.setCheckedGoodsList(checkedGoodsList);
        //        赋值地址信息
        wxCheckOutVO.setCheckedAddress(checkedAddress);
        return wxCheckOutVO;
    }

    @Override
    public WxIndexVO deleteCart(CheckedCartBO checkedCartBO) {
        //        判断user是否为空
        if (GetSubject.getUser() == null) {
            return null;
        }
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andUserIdEqualTo(GetSubject.getUserId()).andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        List<Integer> productIds = checkedCartBO.getProductIds();
        for (Cart cart : carts) {
            for (Integer productId : productIds) {
                if (cart.getProductId().equals(productId)) {
                    cart.setDeleted(true);
                    cartMapper.deleteByPrimaryKey(cart.getId());
                    cartMapper.updateByPrimaryKeySelective(cart);
                }
            }
        }
        BigDecimal goodsAmount = new BigDecimal("0");
        BigDecimal checkGoodsAmount = new BigDecimal("0");
        int goodsCount = 0;
        int checkGoodsCount = 0;
        for (Cart listDTO : carts) {
            goodsAmount = goodsAmount.add(listDTO.getPrice().multiply(new BigDecimal(listDTO.getNumber())));
            goodsCount += listDTO.getNumber();
            if (listDTO.getChecked()) {
                checkGoodsAmount = checkGoodsAmount.add(listDTO.getPrice().multiply(new BigDecimal(listDTO.getNumber())));
                checkGoodsCount += listDTO.getNumber();
            }
        }
//        初始化勾选的内容
        List<Cart> cartList = new ArrayList<>();
        for (Cart cart : carts) {
            if (!cart.getDeleted()) {
                cartList.add(cart);
            }
        }
        WxIndexVO.CartTotalDTO cartTotalDTO = new WxIndexVO.CartTotalDTO();
        cartTotalDTO.setCheckedGoodsAmount(checkGoodsAmount);
        cartTotalDTO.setCheckedGoodsCount(checkGoodsCount);
        cartTotalDTO.setGoodsAmount(goodsAmount);
        cartTotalDTO.setGoodsCount(goodsCount);
        WxIndexVO wxIndexVO = new WxIndexVO();
        wxIndexVO.setCartList(cartList);
        wxIndexVO.setCartTotal(cartTotalDTO);
        return wxIndexVO;
    }

    @Override
    public Integer getCountsByCart() {
//        判断user是否为空
        if (GetSubject.getUser() == null) {
            return 0;
        }
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andUserIdEqualTo(GetSubject.getUserId()).andDeletedEqualTo(false);

        List<Cart> carts = cartMapper.selectByExample(cartExample);
        Integer data = 0;
        for (Cart cart : carts) {
            data += cart.getNumber();
        }

        return data;
    }

    @Override
    public WxIndexVO cartIndexById() {

//        判断user是否为空
        if (GetSubject.getUser() == null) {
            return null;
        }
//        通过工具类获取userID，然后进一步获取user
        Integer userId = GetSubject.getUserId();
//        初始化indexVO类
        WxIndexVO wxIndexVO = new WxIndexVO();
//        从数据库获取Vo类的cartList，并得到里面的内容
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        List<Cart> cartListDTO = cartMapper.selectByExample(cartExample);

        BigDecimal goodsAmount = new BigDecimal("0");
        BigDecimal checkGoodsAmount = new BigDecimal("0");
        int goodsCount = 0;
        int checkGoodsCount = 0;
        for (Cart listDTO : cartListDTO) {

            goodsAmount = goodsAmount.add(listDTO.getPrice().multiply(new BigDecimal(listDTO.getNumber())));
            goodsCount += listDTO.getNumber();
            if (listDTO.getChecked()) {
                checkGoodsAmount = checkGoodsAmount.add(listDTO.getPrice().multiply(new BigDecimal(listDTO.getNumber())));
                checkGoodsCount += listDTO.getNumber();
            }
        }

//        初始化勾选的内容
        WxIndexVO.CartTotalDTO cartTotalDTO = new WxIndexVO.CartTotalDTO();
        cartTotalDTO.setCheckedGoodsAmount(checkGoodsAmount);
        cartTotalDTO.setCheckedGoodsCount(checkGoodsCount);
        cartTotalDTO.setGoodsAmount(goodsAmount);
        cartTotalDTO.setGoodsCount(goodsCount);
//        开始赋值
        wxIndexVO.setCartList(cartListDTO);
        wxIndexVO.setCartTotal(cartTotalDTO);
//        赋值完毕，返回VO
        return wxIndexVO;
    }

    @Override
    public void updateCartByUser(UpdateCartBO updateCartBO) {
//        判断user是否为空
        if (GetSubject.getUser() == null) {
            return;
        }
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andUserIdEqualTo(GetSubject.getUserId()).andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        for (Cart cart : carts) {
            if (cart.getId().equals(updateCartBO.getId())) {
                cart.setGoodsId(updateCartBO.getGoodsId());
                cart.setNumber(updateCartBO.getNumber());
                cart.setProductId(updateCartBO.getProductId());
                cartMapper.updateByPrimaryKeySelective(cart);
            }
        }

    }

}